package com.ted.realm;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;


/**
 * 创建日期:2018年5月4日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:授权的信息<br/>
 */
public class TeddyRealm extends CasRealm {

	/**
	 * 授权,用来判断用户的权限的
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		  // 用户名称
        Object username = principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 根据用户ID查询角色（role），放入到Authorization里。
//        Set<String> roles = userRoleService.getRoleByName(username.toString());
        Set<String> roles = new HashSet<String>();
        info.setRoles(roles);

        // 根据用户ID查询权限（permission），放入到Authorization里。
        Set<String> permissions =  new HashSet<String>();
//        if (roles.size() > 0) {
//            permissions = this.rolePermissionService.getPermissionByRole(roles);
//        }
        info.setStringPermissions(permissions);

        return info;
	}
	
	/**
	 * 验证用户的登录
	 */
	@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //调用父类的方法，然后授权用户
        AuthenticationInfo authc = super.doGetAuthenticationInfo(token);
        
        if(authc == null){
        	return null;
        }
        //获取用户名
        String username = (String) authc.getPrincipals().getPrimaryPrincipal();
        
        //数据库中，查询用户的信息
        Map<String,String> user = new HashMap<String,String>();
        if(username.equals("libo")){
        	user.put("username", "libo");
        	user.put("age", "12");
        }
      
        //设定到session中
        SecurityUtils.getSubject().getSession().setAttribute("user", user);

        return authc;
    }
}
